<template>
  <div class="Shopbag">
    <van-nav-bar title="购物袋" left-text="返回" left-arrow @click-left="onClickLeft" fixed>
      <template #right>
        <div v-if="shopbagData.length>0" @click="isEdit=!isEdit">{{ isEdit?'完成':'编辑' }}</div>

      </template>
    </van-nav-bar>
    <div class="shopbagBg-img">
      <img src="@/assets/images/shopbag_bg.png" alt="">
    </div>

    <div v-if="shopbagData.length==0">
      <van-empty description="购物袋空空如也，快去逛一逛" />
      <van-button round color="#0C34BA" @click="guang" class="gguang">逛一逛</van-button>
    </div>
    <div class="shopbag-box" v-else>
      <div class="shopbag-bg">

        <!-- 懒加载组件 -->
        <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load=" loadData">
          <!-- 在购物车里面的商品 -->
          <div class="shopbag-good" v-for="(item,index) in shopbagData" :key="item.sid">
            <!-- 滑动单元格 -->
            <van-swipe-cell class="swipeCell ">
              <div class="checked-box">
                <van-checkbox @change="simpleSelect" v-model="item.isChecked" />
              </div>
              <div class="card-box">
                <van-card class="b-radius" :price="item.price" :desc="item.enname" :title="item.name+' '+ item.rule" :thumb="item.small_img" />
                <div class="shopbaggood-count">
                  <van-stepper v-model="item.count" theme="round" button-size="22" disable-input @change=" changeShopBagCount(item)" />
                </div>
              </div>
              <template #right>
                <van-button square text="删除" type="danger" class="delete-button" @click="removeOne(index, item.sid)" />
              </template>
            </van-swipe-cell>

          </div>
        </van-list>
        <div v-if="isEdit==false">
          <van-submit-bar :price="tatal" button-text="提交订单" @submit="commit">
            <van-checkbox v-model="isAllChecked" @click="allSelect">全选</van-checkbox>
          </van-submit-bar>
        </div>
        <div v-if="isEdit==true">
          <van-submit-bar :price="tatal" button-text="删除选择" @submit="removeSelected">

            <van-checkbox v-model="isAllChecked" @click="allSelect">全选</van-checkbox>

          </van-submit-bar>

        </div>

      </div>
    </div>

  </div>
</template>

<script>
import '@/assets/less/shopbag.less'
import request from '@/utils/reques'
import qs from 'qs'
export default {
  name: '',
  data() {
    return {
      // 要显示的购物袋商品数据
      shopbagData: [],

      // 是否选中
      isChecked: false,
      // 是否编辑
      isEdit: false,
      // 购物袋商品数量
      count: 2,
      // 是否全选
      isAllChecked: false,
      // 懒加载是否加载
      loading: true,
      // 是否全部加载完成数据
      finished: false,
      // 所有购物袋商品数据
      allShopbagData: [],
      // 下拉加载数量
      dataCount: 8,
      // 开始截取购物袋数据的位置
      startIndex: 0,
      // 订单总金额
      tatal: 0
    }
  },
  created() {
    this.getShopbagData()
    this.sum()
  },
  methods: {
    // 获取购物袋数据
    async getShopbagData() {
      let tokenString = localStorage.getItem('token')

      if (!tokenString) {
        this.$toast('请先登录~')
        return this.$router.push({ name: 'Login' })
      }
      this.$toast.loading({
        message: '获取信息中',
        forbidClick: true,
        duration: 0
      })
      const { data: res } = await request.get('/findAllShopcart', { params: { appkey: this.appkey, tokenString } })
      if (res.code == 700) {
        this.$router.push({ name: 'Login' })
      } else if (res.code == 5000) {
        res.result.map((v) => {
          v.isChecked = false
        })
      }
      this.allShopbagData = res.result
      // console.log(this.allShopbagData)
      // 截取数据
      // 根据开始截取位置和截取数据数量设置购物袋显示数据
      this.shopbagData = this.allShopbagData.slice(this.startIndex, this.startIndex + this.dataCount)
      // console.log(this.shopbagData)
      this.startIndex += this.dataCount
      // 未加载数据
      this.loading = false
      this.$toast.clear()
    },
    onClickLeft() {
      this.$router.go(-1)
    },
    // 懒加载购物车数据
    loadData() {
      setTimeout(() => {
        // 在allshopbagdata截取数据
        let data = this.allShopbagData.slice(this.startIndex, this.startIndex + this.dataCount)
        this.startIndex += this.dataCount
        // 把新数据加入到shopbagData中
        this.shopbagData.push(...data)
        this.isAllChecked = false
        // 如果当前数据不足8条，下次不截取数据
        if (data.length < this.dataCount) {
          this.finished = true
        } else {
          // 每次触发onload事件的时候，都需要将loading修改为false
          this.loading = false
        }
      }, 1500)
    },
    // 修改购物车数量
    async changeShopBagCount(item) {
      try {
        let sid = item.sid
        let count = item.count
        let tokenString = localStorage.getItem('token')
        if (!tokenString) {
          this.$toast('请先登录~')
          return this.$router.push({ name: 'Login' })
        }
        const { data: res } = await request.post('/modifyShopcartCount', qs.stringify({ appkey: this.appkey, tokenString, sid, count }))
        // console.log(res)
        if (res.code == 6000) {
          // 调用选择
          if (item.isChecked) {
            // 金额重新统计
            this.sum()
          }
        }
        this.$toast.clear()
      } catch (error) {
        this.$toast.clear()
      }
    },
    // 全选
    allSelect() {
      this.shopbagData.map((v) => {
        v.isChecked = this.isAllChecked
      })
      this.sum()
    },
    //单选
    simpleSelect() {
      this.sum()
      for (let i = 0; i < this.shopbagData.length; i++) {
        if (!this.shopbagData[i].isChecked) {
          // 选择单选时，全选需要失效
          this.isAllChecked = false
          return
        }
      }
      this.isAllChecked = true
    },
    // 单个删除
    async removeOne(index, sid) {
      let tokenString = localStorage.getItem('token')

      if (!tokenString) {
        this.$toast('请先登录~')
        return this.$router.push({ name: 'Login' })
      }
      const { data: res } = await request.post('/deleteShopcart', qs.stringify({ appkey: this.appkey, tokenString, sids: JSON.stringify([sid]) }))
      if (res.code == 700) {
        this.$router.push({ name: 'Login' })
      } else if (res.code == 7000) {
        this.shopbagData.splice(index, 1)
      }
      this.$toast('删除成功')
      this.sum()
    },
    // 判断是否选中商品
    isSelectProduct() {
      for (let i = 0; i < this.shopbagData.length; i++) {
        if (this.shopbagData[i].isChecked) {
          return true
        }
      }
    },
    // 删除选择的商品
    async removeSelected() {
      try {
        let isHas = this.isSelectProduct()
        if (!isHas) {
          this.$toast('请选择要删除的商品')
        } else {
          let sids = []
          this.shopbagData.map((v) => {
            if (v.isChecked) {
              sids.push(v.sid)
            }
          })
          // 调用接口删除
          let tokenString = localStorage.getItem('token')

          if (!tokenString) {
            this.$toast('请先登录~')
            return this.$router.push({ name: 'Login' })
          }
          const { data: res } = await request.post('/deleteShopcart', qs.stringify({ appkey: this.appkey, tokenString, sids: JSON.stringify([sids]) }))
          if (res.code == 700) {
            this.$router.push({ name: 'Login' })
          } else if (res.code == 7000) {
            //  如果删除成功，则移除页面的商品
            // 移除页面的数据
            for (let i = 0; i < this.shopbagData.length; i++) {
              if (this.shopbagData[i].isChecked) {
                this.shopbagData.splice(i, 1)
                i--
              }
            }
            // 删除完了之后重新计算总价
            this.sum()
          }
          this.$toast(res.msg)
        }
        // sid 购物袋的sid集合
      } catch (error) {
        this.$toast.clear()
      }
    },
    // 计算商品的总价格
    sum() {
      this.tatal = 0
      this.shopbagData.map((v) => {
        if (v.isChecked) {
          this.tatal += v.price * v.count * 100
        }
      })
      // console.log(this.tatal)
    },
    // 提交订单
    commit() {
      // 是否选择
      let isHas = this.isSelectProduct()
      if (!isHas) {
        this.$toast('请选择商品')
        return
      }
      // 商品sids集合
      let sids = []
      this.shopbagData.map((v) => {
        if (v.isChecked) {
          sids.push(v.sid)
        }
      })

      // 跳转到支付页面
      this.$router.push({ name: 'Pay', query: { sids: sids.join('-') } })
    },
    // 逛一逛
    guang() {
      this.$router.push({ name: 'Home' })
    }
  }
}
</script>

<style lang="less" scoped>
</style>